﻿using ED.Common.BaseModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace ED.Common.Filters
{
    public class ModelValidationFilter : IAsyncActionFilter, IFilterMetadata
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            ModelStateDictionary modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                string error = string.Empty;
                foreach (string key in modelState.Keys)
                {
                    ModelStateEntry state = modelState[key];
                    if (state.Errors.Any())
                    {
                        ModelError errorInfo = state.Errors.First();
                        string ex = ((errorInfo.Exception == null) ? "" : errorInfo.Exception.ToString());
                        error = (string.IsNullOrEmpty(errorInfo.ErrorMessage) ? ex : errorInfo.ErrorMessage);
                        break;
                    }
                }

                ResponseOutput<bool> response = ResponseOutput.NotOk(error);
                 JsonResult result = (JsonResult)(context.Result = new JsonResult(response));

            }
            else
            {
                await next();
            }
        }
    }
}
